<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>策略模式验证表单</title>
</head>
<body>
    <button onclick="submit2('jack', '15234', '154556566433')">提交</button>

    <script>
        // 非策略模式
        function submit(userName, password, phoneNumber){
            if(userName.length < 2){
                alert('用户名长度不得小于2')
                return false
            }else if(password.length < 6){
                alert('密码长度不得小于6')
                return  false
            }else if(phoneNumber.length < 8){
                alert('手机号码长度不得小于8')
                return  false
            }
        }



        // 策略模式

        // 校验表单策略类
        const startegy = {
            userName: function(userName,errmsg){
                if(userName.length < 2){
                    return errmsg
                }
            },
            password: function(password, minlength,errmsg){
                if(password.length < minlength){
                    return  errmsg
                }
            },
            phoneNumber: function(phoneNumber, errmsg){
                if(phoneNumber.length < 8){
                    return  errmsg
                }
            }
        }

        // 校验表单环境类
        
        let submit2 = function(userName, password, phoneNumber){
            let validator = new Validator()
            
            // 验证类
            validator.add(userName, 'userName', '用户名长度不得小于2')
            validator.add(password, 'password:6', '密码长度不得小于6')
            validator.add(phoneNumber, 'phoneNumber', '手机号码长度不得小于8')

            // 开始校验 返回结果
        
            let errMsg = validator.start()

            if(errMsg){
                alert(errMsg)
            }else{
                console.log('恭喜你,校验成功')
            }
        }

        // 编写 validtor 类
        function Validator(){

            // 校验规则列表
            this.cache = []
        }

        Validator.prototype.add = function(value, rule, errMsg){
            let ary = rule.split(':')
            this.cache.push(function(){
                // 取出用户规则
                let starte = ary.shift()
                ary.unshift(value)
                ary.push(errMsg)
                // 环境类操作策略类
                return startegy[starte](...ary)
            })
        }

        Validator.prototype.start = function(){

            // 循环校验
            for(let i = 0;i < this.cache.length; i++){
                const errMsg = this.cache[i]()
                console.log(errMsg == true , errMsg)
                if(errMsg) return errMsg
            }
        }
    
    </script>
</body>
</html>